<template>
  <basic-dialog
    :visible.sync="visible"
    :title="title"
    :width="'50%'"
    :handleClose="handleCloseDialog"
    :handleOpened="handleOpenDialog"
    :handleOk="handleSubmit"
    :loadingBtn="submitLoading"
    :okText="'提交'"
  >
    <el-row>
      <el-form class="table_form_wrap" ref="formData" :rules="rules" :model="formData" label-width="140px">
        <el-form-item v-if="uuid" label="计量单位组ID：" prop="uuid">
          <el-input
            disabled
            v-model="formData.uuid"
            :maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="计量单位组名称：" prop="groupName">
          <el-input
            v-model="formData.groupName"
            :maxlength="20"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </el-row>
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import {
  getUnitGroupDetailService,
  updateUnitGroupService,
} from '@/api/basics/unitManage/unitGroup';

export default {
  name: 'AddUnit',
  components: {
    BasicDialog,
  },
  props: {
    visible: {
      type: Boolean
    },
    uuid: {
      type: [String, Number],
    }
  },
  computed: {
    title () {
      return this.uuid ? '编辑' : '新增'
    }
  },
  data () {
    return {
      submitLoading: false,
      formData: {
        uuid: '', // 计量单位组Uuid
        groupName: '', // 单位组名称
      },
      rules: {
        groupName: [
          { required: true, message: '请输入计量单位组名称', trigger: 'blur' },
        ],
      }
    };
  },
  methods: {
    handleOpenDialog () {
      this.$refs.formData.resetFields()
      if (this.uuid) {
        this.getUnitGroupDetail(this.uuid)
      }
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$emit('update:visible', false);
    },
    initFormData (data) {
      const {
        uuid,
        groupName,
      } = data;
      this.formData = {
        uuid,
        groupName,
      }
    },
    // 获取计量单位详情
    async getUnitGroupDetail (uuid) {
      const res = await getUnitGroupDetailService({ uuid })
      if (res) {
        this.initFormData(res.retData)
      }
    },
    handleSubmit () {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.editUnitGroup()
        }
      })
    },
    // 编辑计量单位
    async editUnitGroup () {
      const res = await updateUnitGroupService(this.formData, state => { this.submitLoading = state })
      if (res) {
        this.$message.success('操作成功')
        this.handleCloseDialog();
        this.$emit('getTableData')
      }
    },
  }
};
</script>
